package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.xmy.study.entity.StudentAccount;
import com.xmy.study.exception.CommonException;
import com.xmy.study.respons.ProfileResult;
import com.xmy.study.service.IStudentAccountService;
import com.xmy.study.util.ResultCode;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class WebBaseController extends BaseController {

    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected Long schoolId = 0L;

    protected Integer yearPart = 2023;

    protected Integer quarterNum = 4;

    /**
     * 学生信息
     */
    protected StudentAccount studentAccountInfo;

    protected Long studentId;

    protected Long classTypeId;

    protected Integer yearClassId;

    protected Long courseVersionId;//学习版本id

    protected Integer status;

    private final String onlineData = "onlineData";


    //为了后来系统的兼容性，应该所有对象都是以json的方式进行保存
    @Autowired //如果给redis中保存数据会使用默认的序列化机制，导致redis中保存的对象不可视
    RedisTemplate<Object, Object> redisTemplate;

    @Value("${online-config.userDataStatistics:5}")
    protected int configUserDataStatistics;

    @Autowired
    @Lazy
    IStudentAccountService iStudentAccountService;

    //使用shiro获取
    @ModelAttribute
    public void setResAnReq(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;

        //获取session中的安全数据
        Subject subject = SecurityUtils.getSubject();
        //1.subject获取所有的安全数据集合
        PrincipalCollection principals = subject.getPrincipals();
        if (principals != null && !principals.isEmpty()) {
            //2.获取安全数据
            profileResult = (ProfileResult) principals.getPrimaryPrincipal();

            studentAccountInfo = (StudentAccount) this.profileResult.getStudentAccount();

            studentId = studentAccountInfo.getStudentId();
            this.status = studentAccountInfo.getStatus();

            //设置redis_key 自动升班
            String classTypeIdKey = "classTypeIdfredis::"+studentId;
            Object o = redisTemplate.opsForValue().get(classTypeIdKey);
            if (ObjectUtils.isNotEmpty(o)){
                classTypeId = (Long) o;
            } else {
                classTypeId = studentAccountInfo.getClassTypeId();
            }

            yearClassId = studentAccountInfo.getYearClassId();

            yearPart = studentAccountInfo.getYearPart();

            quarterNum = studentAccountInfo.getQuarterNum();

            schoolId = studentAccountInfo.getSchoolId();

            courseVersionId = studentAccountInfo.getCourseVersionId();

            //10005 唯一设备登录
            String sid = (String) subject.getSession().getId();
            String username = studentAccountInfo.getAccount();
            //设置redis_key
            String userRedisKey = "usershiroifredis"+username;
            //读取redis
            Object ifSid = redisTemplate.opsForValue().get(userRedisKey);
            if (ifSid != null && !ifSid.toString().isEmpty() && !sid.equals(ifSid)) {
                throw new CommonException(ResultCode.SHIROIFUSERKEY);
            }
            //写入pk的redis
            setRedis(studentId,"inviterName",studentAccountInfo.getStudentName());
            setRedis(studentId,"yearClassId",classTypeId);
            setRedis(studentId,"yearPart",studentAccountInfo.getYearPart());
            setRedis(studentId,"quarterNum",studentAccountInfo.getQuarterNum());
            setRedis(studentId,"courseVersionId",studentAccountInfo.getCourseVersionId());
        }else {
            //临时添加看错数据，后面删除
            redisTemplate.opsForValue().set("error139:"+this.studentId,"安全值数据不存在");
        }
    }

    private void setRedis(Long studentId, Object hKey, Object value) {
        //设置redis
        String redisKey = "pkBattle::" + studentId;
        redisTemplate.opsForHash().put(redisKey,hKey, value);
//        redisTemplate.expire(redisKey, redisOutTime, TimeUnit.MINUTES);//过期时间

    }
    @Value("${spring.redis.pkOutTime:180}")
    private int redisOutTime;

}
